<?php

namespace app\api\controller;

use app\common\controller\Api;

use addons\epay\library\Service;
use app\common\model\User as UserModel;



use think\Config;
use think\Db;

/**
 * 回调类
 */
class Notify extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->model=model('admin/User');
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->coursesorder=model('admin/courses/Order');
        $this->courses_moneylog=model('admin/courses/Moneylog');
        $this->courses_courses=model('admin/courses/Courses');
        $this->teacher=model('admin/user/Teacher');
        $this->usersignup=model('admin/mechanism/Usersignup');
        $this->user=model('admin/User');


       // $this->courses_moneylog
        // $this->order = model('admin/order/Order'); //学生类型
    }
    //开通会员回调

    /**
     * 购买课程回调
     * @throws \think\exception\PDOException
     */


    public function courses_notify(){

        $paytype =$this->request->param('paytype');
        $method =$this->request->param('method');
        $data = file_get_contents('php://input');
        if($paytype=='wechat'){
            $data = json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA));
            $fp=fopen('./wechatcoursesapplylog.txt','a+');//public/log.txt
            fwrite($fp,var_export("（订单参数）：$data ------",true));
            fclose($fp);
        }
        if($paytype=='wechat'){
            $order_sn = $data['out_trade_no'];
            $transaction_id=$data['transaction_id'];
            $payamount=$data['total_fee']/100;
        }


        try{
            db()->startTrans();
            $orderInfo = $this->coursesorder->get(['order_sn'=>$order_sn]);
           if($orderInfo['paystate']==0){
               $orderInfo->save(['paystate'=>1,'method'=>$method,'transactionid'=>$transaction_id,'paytime'=>time(),'orderstate'=>3,'payamount'=>$payamount,'paytype'=>$paytype,'method'=>'scan']);
              $coursesInfo= $this->courses_courses->where('id',$orderInfo->courses_courses_id)->find();

              $teacherInfo= $this->teacher->where('id',$coursesInfo->user_teacher_id)->find();
               $this->courses_moneylog::Create(['admin_id'=>$teacherInfo['admin_id'],'money'=>$payamount,
                   'before'=>$teacherInfo['money'],'after'=>$teacherInfo['money']+$payamount,'memo'=>'购买课程']);

               $this->teacher->where('admin_id',$coursesInfo->admin_id)->setInc('money',$payamount);
               if($orderInfo['score']>0){
                   UserModel::score(-$orderInfo['score'], $orderInfo['uid'], '支付订单扣除订单号'.$orderInfo['order_sn']);
               }

              if($payamount>=1){
                  UserModel::score($payamount, $orderInfo['uid'], '支付订单赠送订单号'.$orderInfo['order_sn']);
              }


           }

            db()->commit();
        }catch (Exception $e){
            db()->rollback();
            if($paytype=='wechat'){
                $fp=fopen('./wechatcoursesapplylog.txt','a+');//public/log.txt
                fwrite($fp,var_export("微信支付有误（订单）：$order_sn ------",true));
                fwrite($fp,var_export($e->getMessage(),true));
                fclose($fp);
            }

        }
        if($paytype=='wechat'){
            if (!Service::checkNotify('wechat')) {
                $fp=fopen('./wechatcoursesapplylog.txt','a+');//public/log.txt
                fwrite($fp,var_export('签名错误 ------",:'.$order_sn,true));
                fclose($fp);
                echo '签名错误';
                return;
            }

        }

        echo "success";
        exit;



    }

//报名回调
    public  function exam_notify(){

        $paytype =$this->request->param('paytype');
       // $method =$this->request->param('method');
        $data = file_get_contents('php://input');
        if($paytype=='wechat'){
            $data = json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA));
            $fp=fopen('./wechatexamapplylog.txt','a+');//public/log.txt
            fwrite($fp,var_export("（订单参数）：$data ------",true));
            fclose($fp);
        }


        $data=json_decode($data,true);
//        $paytype='wechat';
//        $data['out_trade_no']='SN2024052140381';
//        $data['transaction_id']='4200002144202405211165868942';
        if($paytype=='wechat'){
            $order_sn = $data['out_trade_no'];
            $transaction_id=$data['transaction_id'];
            $payamount=$data['total_fee']/100;
        }


        $fp=fopen('./wechatexamapplylog.txt','a+');//public/log.txt
        fwrite($fp,var_export("（订单号）：$order_sn ------",true));
        fclose($fp);

        try{
            db()->startTrans();
            $orderInfo = $this->usersignup->get(['order_sn'=>$order_sn]);
            if($orderInfo['paystate']==0){
                $this->usersignup->where(['order_sn'=>$order_sn])->update(['paystate'=>1,'method'=>'scan','paytype'=>$paytype,'method'=>'scan','transactionid'=>$transaction_id,'paytime'=>time(),'step'=>'已报名']);
//                if($payamount>=1){
//                    $this->user->where('id',$orderInfo['user_id'])->setInc('score',$payamount);
//                }

                if($orderInfo['usered_score']>0){
                    UserModel::score(-$orderInfo['usered_score'], $orderInfo['user_id'], '支付订单扣除订单号'.$orderInfo['order_sn']);
                }

                if($payamount>=1){
                    UserModel::score($payamount, $orderInfo['user_id'], '支付订单赠送订单号'.$orderInfo['order_sn']);
                }

            }

            db()->commit();
        }catch (Exception $e){
            db()->rollback();
            if($paytype=='wechat'){
                $fp=fopen('./wechatexamapplylog.txt','a+');//public/log.txt
                fwrite($fp,var_export("微信支付有误（订单）：$order_sn ------",true));
                fwrite($fp,var_export($e->getMessage(),true));
                fclose($fp);
            }

        }
        if($paytype=='wechat'){
            if (!Service::checkNotify('wechat')) {
                $fp=fopen('./wechatexamapplylog.txt','a+');//public/log.txt
                fwrite($fp,var_export('签名错误 ------",:'.$order_sn,true));
                fclose($fp);
                echo '签名错误';
                return;
            }

        }

        echo "success";
        exit;



    }


}
